import CryptoJS from 'crypto-js'

export interface CryptoType {
  /**
   * 动态生成指定长度Key
   *
   * @param num key的长度
   */
  generatekey(num: number): string
  /**
   * AES加密
   *
   * @param contentStr 内容字符串
   * @param keyStr 密钥Key
   */
  encrypt(contentStr: string, keyStr: string): string
  /**
   * AES解密
   *
   * @param securityStr 加密字符串
   * @param keyStr 密钥Key
   */
  decrypt(securityStr: string, keyStr: string): string
}

class AesUtils implements CryptoType {
  defaultKey = 'abcdsxyzhkj12345'
  /**
   * 动态生成指定长度Key
   *
   * @param num key的长度
   */
  generatekey(num: number) {
    const library = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let key = ''
    for (let i = 0; i < num; i++) {
      const randomPoz = Math.floor(Math.random() * library.length)
      key += library.substring(randomPoz, randomPoz + 1)
    }
    return key
  }
  /**
   * AES加密
   *
   * @param contentStr 内容字符串
   * @param keyStr 密钥Key
   */
  encrypt(contentStr: string, keyStr: string) {
    keyStr = keyStr ? keyStr : this.defaultKey //判断是否存在ksy，不存在就用定义好的key
    const key = CryptoJS.enc.Utf8.parse(keyStr)
    const srcs = CryptoJS.enc.Utf8.parse(contentStr)
    const encrypted = CryptoJS.AES.encrypt(srcs, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.toString()
  }
  /**
   * AES解密
   *
   * @param securityStr 加密字符串
   * @param keyStr 密钥Key
   */
  decrypt(securityStr: string, keyStr: string) {
    keyStr = keyStr ? keyStr : this.defaultKey
    const key = CryptoJS.enc.Utf8.parse(keyStr)
    const decrypt = CryptoJS.AES.decrypt(securityStr, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    })
    return CryptoJS.enc.Utf8.stringify(decrypt).toString()
  }
}

const aesUtils: AesUtils = new AesUtils()

export default aesUtils
